import "../../../../scss/activity/group_buy/group_buy.scss";
import $ from "jquery";
import "../../../utils/weui";
import moment from "moment";
import ps from "../../../common/group_variable";
import Vue from "vue";
import ReadSection from "../../components/readSection";
import FuncBanner from "../../components/funcbanner";
import CtrlPlay from "../../components/ctrlplay";
import UserJoin from "../../components/userJoin";
import com from "../../../utils/common";
import count from "../../../utils/countdown";
import wxtool from "../../components/weixin";

import NoticePop from "../../components/noticeWay";
import setWxShare from "../../components/setWxShare";
import SharePop from "../../components/sharePop";
import viewAddFooter from "../../components/viewAddFooter";
import wxpay from "../../components/wxpay";

let user = wxtool.getWxUserinfo();
console.log(user);
// user.openid = "oiC0jwK44HLzbcnEcMyyyyyRkBr888e477211A"
$(function () {
  let page = {
    _actid: com.getUrlParam("actid") ? com.getUrlParam("actid") : 1,
    _joinid: com.getUrlParam("joinid") ? com.getUrlParam("joinid") : 1,
    _ispreview: com.getUrlParam("preview") ? com.getUrlParam("preview") : 0,
    _appdata: {
      partinstatusall: ps, // 所有状态
      partinstatus: ps.JoinJustNow, //当前状态
      countDown: {
        days: "xx",
        hours: "xx",
        minutes: "xx",
        seconds: "xx"
      },
      // 默认无团
      GroupAll: []
    },
    _app: {},
    _init: function () {
      let self = this;
      // 获取活动数据
      com.ajax({
        url: "/act/groupby/getActDetial",
        data: {
          ActId: self._actid,
          Joinid: self._joinid,
          Openid: user.openid,
        },
        ok: function (data) {
          console.log(data);
          let temp = data["msg"];
          if (temp !== "fail" && typeof temp === "object") {
            temp.Actid = self._actid;
            temp.Prizes = JSON.parse(temp.Prizes);
            temp.Other = JSON.parse(data["msg"]["Other"])
            temp.StartDate = moment(temp.StartTime).format("YYYY-MM-DD HH:mm");
            temp.EndDate = moment(temp.EndTime).format("YYYY-MM-DD HH:mm");
            temp.Content = JSON.parse(temp.Content);

            $("#PageTitle").html(temp.Title)

            // 获得当前页面的团信息
            if(self._joinid > 1){
              let GroupNow = [];


              GroupNow.push({
                Name:data['leader'].Name,
                JoinDate:moment(data['leader'].CreateTime).format("YYYY-MM-DD HH:mm"),
                Identity:'head',
              })
              for (let i = 0; i < data['partners'].length; ++i) {
                GroupNow.push({
                  Name: data['partners'][i].Name,
                  JoinDate: moment(data['partners'][i].CreateTime).format("YYYY-MM-DD HH:mm"),
                  Identity: 'member',
                })
              }

              temp.GroupNow = GroupNow;
              temp.GroupPrice = data['leader'].Current;
              console.log(GroupNow.length)
            }else{
              temp.GroupNow = data['group'];
            }

            temp.GroupArr = temp.Prizes.GroupArr;
            temp.GroupAll = data['group'];
            console.log(temp.GroupAll);
            temp.isPartIn = data['isPartIn'];
            temp.isJoiner = data['isJoiner'];
            temp.leader = data['leader'];
            temp.partners = data['partners'];
            // 分享相关信息
            let ShareMsg = {};
            ShareMsg.ShareImg = temp.ShareImg;
            ShareMsg.ShareTitle = temp.ShareTitle ? temp.ShareTitle : temp.Title;
            ShareMsg.ShareContent = temp.ShareContent;
            self._appdata.ShareMsg = ShareMsg;
            if (self._joinid > 1) {
              let JoinerMsg = {};
              JoinerMsg.Name = data["extra"].Name;
              self._appdata.JoinerMsg = JoinerMsg;
            }
            // 回到自己页面(当打开页面的用户已经有团时)
            if(data["Joinid"] != self._joinid && data["Joinid"] &&  data["Joinid"] > 1){
              window.location.href = "/dist/activity/group_buy/group_buy.html?actid=" + self._actid + "&joinid=" + data["Joinid"]
            }
            /* 加载状态*/
            self._appdata.partinstatus = self._checkActStatus(data);
            let ActStatus = {};
            ActStatus.partinstatusall = ps;
            ActStatus.partinstatus = self._appdata.partinstatus;
            self._appdata.ActStatus = ActStatus;

            /* 加载状态*/
            $.extend(self._appdata, temp);
            console.log(self._appdata);
            self._loadTemp()
          }
        }
      });
    },

    _checkActStatus:function (act) {
      let self = this;
      console.log(act);
      let temp = act['msg'];
      let start = moment(temp.StartTime);
      let end = moment(temp.EndTime);
      let now = moment();
      //判断活动是否开始
      if (now.isBefore(start)) {
        return ps.AtActInActiveStart
      }
      //判断活动是否开始
      if (now.isAfter(end)) {
        return ps.AtActInActiveEnd
      }

      // 当用户打开他人团时,此时用户既不是团员也不是团长
      if (self._joinid > 1 && !act.isPageJoin && !act.isPartIn) {
        return ps.ParterLook
      }
      // 当用户是参与者进入自己页面时
      if(act.isJoiner && ! act.isPartIn){
        return ps.JoinDone
      }
      //判断帮忙者是否参与过活动(帮忙者是参与者)
      if (act.isPartIn) {
        return ps.ParterDone
      }

      return ps.JoinJustNow
    },
    // 加载vue 模板
    _loadTemp: function () {
      let self = this;
      Vue.component("g-section", ReadSection)
      Vue.component("func-banner", FuncBanner);
      Vue.component("music", CtrlPlay);
      Vue.component("user-join", UserJoin);
      Vue.component("notice-pop", NoticePop);
      Vue.component("add-msg", viewAddFooter);
      Vue.component("share-pop", SharePop);
      self._app = new Vue({
        el: "#app",
        data: self._appdata,
        methods: {
          getReadSection: function (val) {
            console.log(val)
            this.Section = val["Section"];
          },
          showRules: function () {
            $(".rule").show()
            com.showCenter($(".Pop-ups_tem"));
          },
          showGroup: function () {
            $(".rule").show()
            com.showCenter($(".all_group"));
          },
          AlertJoinPop: function (joinid) {
            let JoinerId = joinid;
            let appself = this;
            let msg = '<p style="text-align:left;color:#333;">①报名前可先联系商家，确认活动真实性以及记录联系方式哦！<br/>②如发现虚假活动，请在客牛公众号回复我们。</p>';
            layer.open({
              content: msg
              , btn: ['确定', '取消'],
              yes: function () {
                layer.closeAll();
                $('.pop_mask').show();
                com.showCenter($(".pop_user_msg"))
                if(JoinerId){
                  $("#signUp").html("<a href='#'>提交</a>")
                  console.log(JoinerId)
                  let joinid = JoinerId > 1 ? JoinerId :self._joinid;
                  console.log(JoinerId)
                  $("#signUp > a").click(function () {
                    appself.actTakePartInOnce(joinid)
                  })
                }
              }
            });
          },
          // 提交报名信息
          UserJoinAct: function (data) {
            let JoinData = {};
            JoinData.Actid = self._actid;
            JoinData.Joinid = self._joinid;
            JoinData.ActivityCat = "group_buy/group_buy";
            JoinData.Name = data["Name"];
            JoinData.Mobile = data["Mobile"];
            JoinData.Other = data["Other"];
            JoinData.Openid = user.openid;
            console.log(data);
            console.log(JoinData);
            com.ajax({
              url: "/act/groupby/joinGroupBy",
              method: "post",
              data: JoinData,
              ok: function (data) {
                console.log(data);
                let detail = data['joinin'];
                if (data["msg"] == "ok") {
                  com.ajax({
                    url: "/wx/createOrder",
                    data: {
                      fee: 1,
                      reqUrl: window.location.href,
                      openid: user.openid,
                      actid: detail.ActivityId,
                      joinid: detail.Id,

                    },
                    ok: function (data) {
                      console.log(data)
                      $.extend(data,{
                        openid: user.openid,
                        actid: detail.ActivityId,
                        joinid: detail.Id,
                      })

                      //进入支付流程
                      data.ok = function () {
                        window.location = "/dist/activity/group_buy/group_buy.html?actid=" + self._actid + "&joinid=" + detail.Id;
                      }
                      data.fail = function () {
                        console.log("删除" +detail.ActivityId)
                        com.ajax({
                          url:"/act/deleteJoiner",
                          data:{
                            Openid: user.openid,
                            Actid: detail.ActivityId,
                            Joinid: detail.Id,
                          },
                          ok:function (data) {
                            console.log(data)
                            if(data["res"] > 0){
                              com.alertDialog("您已取消支付");
                              $(".pop_mask").hide()
                            }
                          }
                        })
                      }
                      wxpay(data)
                    }
                  });
                }else{
                  com.alertDialog("你已经参加过活动,请勿重复参加")
                }
              }
            })
          },

          // 返回自己页面
          BackMine: function () {
            self._getJoinByOpenid(1)
          },

          // 发送给朋友
          SendFriend: function () {
            $(".notice_msg").show()
            com.showCenter($('.sign-suc'))
          },
          actTakePartInOnce: function (joinid) {
            let JoinData = {};
            JoinData.Name = $("#regname").val()
            JoinData.Mobile = $.trim($("#mobile").val())
            JoinData.Actid = self._actid;
            JoinData.Joinid = joinid;
            JoinData.Catgory = "group_buy/group_buy";

            JoinData.Openid = user.openid;
            console.log(JoinData);
            if(!com.CheckMobile(JoinData.Mobile)){
              com.alertDialog("号码错误,请核对")
              return
            }
            com.ajax({

              url: "/act/groupby/takePartInGroupBy",
              method: "post",
              data: JoinData,
              ok: function (data) {
                console.log(data);
                let detail = data['partdetail'];
                if (data["msg"] == "ok") {
                  com.ajax({
                    url: "/wx/createOrder",
                    data: {
                      fee: 1,
                      reqUrl: window.location.href,
                      openid: user.openid,
                      actid: detail.ActivityId,
                      joinid: detail.Id,
                    },
                    ok: function (data) {
                      //进入支付流程
                      data.ok = function () {
                        window.location = "/dist/activity/group_buy/group_buy.html?actid=" + self._actid + "&joinid=" + detail.JoinerId;
                      }

                      data.fail = function () {
                        console.log("删除" +detail.ActivityId)
                        com.ajax({
                          url:"/act/deleteParter",
                          data:{
                            Actid: detail.ActivityId,
                            Joinid: detail.JoinerId,
                            Partid:detail.Id,
                          },
                          ok:function (data) {
                            console.log(data)
                            if(data["res"] > 0){
                              com.alertDialog("您已取消支付");
                              $(".pop_mask").hide()
                            }
                          }
                        })
                      }
                      wxpay(data)
                    }
                  });
                }else if(data["msg"] == "full"){
                  com.alertDialog("团已满,请找其他团吧!")
                }else{
                  com.alertDialog("你已经参加过活动,请勿重复参加")
                }
              }
            })
          }
        }
      })

      self._analysisStatus();
      self._afterTemp();
    },

    // 根据状态判断数据传输,页面交互
    _analysisStatus: function () {
      let self = this;
      if (self._ispreview) {

        $(".preview-footer a:first-child").attr("href", "/dist/activity/group_buy/group_buy_edit.html?actid=" + self._actid)
        $(".preview-footer a:last-child").attr("href", "/dist/activity/group_buy/group_buy.html?actid=" + self._actid)
      }
      // 用户信息(当打开的是已经有用户报名的链接时)(当是用户打开时)
      if (self._joinid > 1) {
        // 检测是否帮忙已经帮忙(是否已经在伙伴里面)
        // 每次用户打开链接都填充分享内容
        let shareData = {
          ShareImg: self._appdata.ShareMsg.ShareImg,
          ShareContent: self._appdata.ShareMsg.ShareContent,
        }
        console.log(self._appdata.ShareMsg)
        let shareTitle = self._appdata.ShareMsg.ShareTitle;
        let joinerMsg = self._appdata.JoinerMsg;
        console.log(joinerMsg["Name"])
        shareData.ShareTitle = joinerMsg.Name + "正在参加" + shareTitle;
        setWxShare.SetShare(shareData)
      }
      else {
        if (!self._ispreview) {
          // 没有人报名时的情况(大概率商家页)
          // 当是商家保存完活动打开页面后
          let checkEditUser = com.getdb(self._actid);
          if (checkEditUser) {
            $(".share_mask").show();
            com.showCenter($(".share_pop"));
            com.savedb(self._actid, false)
          }
          let shareData = {
            ShareTitle: self._appdata.ShareMsg.ShareTitle,
            ShareImg: self._appdata.ShareMsg.ShareImg,
            ShareContent: self._appdata.ShareMsg.ShareContent,
            Actid: self._actid,
          }
          setWxShare.SetShare(shareData)
        }
      }
      // 跳出报名成功弹窗(此时标识用户在自己页面)
      if (self._appdata.partinstatus == self._appdata.partinstatusall.JoinDone) {
        let saveKey = user.openid + self._actid;
        let pageActId = com.getdb(saveKey);
        // 当当前用户第一次打开页面时(此时没有存储活动id)
        if (pageActId != self._actid) {
          com.savedb(saveKey, self._actid);
          $('.notice_msg').show()
          com.showCenter($('.sign-suc'));
          // 点击页面自动刷新
          $("#app").on("click", ".sign-suc-footer,.mask", function () {
            $(".mask,.notice_msg,.sign-suc").hide();
          });
        }
      }
    },
    _afterTemp: function () {
      let self = this;
      let main = {
        closePop: function () {
          // 关闭弹窗
          $(".Pop-ups_tem,.mask,.all_group,.pop_mask").hide();
        },
      };
      // 倒计时
      let countDownTime = setInterval(function () {
        let timeRecord = count.computedTime(moment(self._app.EndDate).format("X"));
        if (timeRecord) {
          self._app.countDown = timeRecord;
        } else {
          self._app.partinstatus = self._app.partinstatusall.AtActInActiveEnd;
          clearInterval(countDownTime)
        }
      }, 1000);
      $(".Pop-ups_close,.sure_rules,.close,.pop_mask").click(main.closePop); // 关闭弹窗


      $(".pop_user_msg,.share_pop").click(function (event) {
        event.stopPropagation();
      });
    },
  }
  page._init();
});
